<?php
/**
 * Gére les requetes et reponse de flux HTML 
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class HtmlController
{	
	protected $_userMembership;
	protected $_htmlLayout;
	protected $_idLayout;
	protected $_htmlContent;
	protected $_jsScript;
	protected $_idPage;
	protected $_codePage;
	protected $_descPage;
	protected $_keywordsPage;
	protected $_isSecurePage;
	protected $_siteId;
	protected $_siteUrl;
	
    /**
    * Constructor
    * Ouvert ou prolonge la session
    * 
    * @return void
    */    
    public function __construct () {
		ob_start();
		session_start();
		$this->_userMembership = new Membership();
		$this->_isSecurePage = false;
    }
	
 	/**
	* Recupere en base de données les informations de la page a afficher
	* et les stockent dans des propriétés de l'instance
	* 
	*/
 	public function getPageContent ( ) {
		$currentUrl = $this->buildUrl($_SERVER['REQUEST_URI']);

		$findSite = true;
		if (isset($_SESSION['SiteId'])) {
			if (strpos($currentUrl, $_SESSION['SiteUrl']) === 0) { //startwith
				$this->_siteId = $_SESSION['SiteId'];
				$this->_siteUrl = $_SESSION['SiteUrl'];
				$findSite = false;
			}
		} 
		
		if ($findSite) {
			DbConnection::getInstance()->Execute(
				'select id, url from sys_site where <s:url/> LIKE CONCAT(`url`, \'%\')', 
				array( 's:url' => $currentUrl));	
					
			if ( $row = DbConnection::getInstance()->nextRow()) {
				$i = 0;
				$this->_siteId = $_SESSION['SiteId'] = $row[$i++];
				$this->_siteUrl = $_SESSION['SiteUrl'] = $row[$i++];
			} else {
				header('HTTP/1.0 404 Not Found');
		  		exit("<h1>404 Not Found</h1>\nThe web site could not be found.");			
			}
		}
		
		$this->_codePage = (isset($_GET['p']))? $_GET['p'] : '';
		
		if (isset($_POST['p']))
			$this->_codePage = $_POST['p'];
			
		if ($this->_codePage != '') {
			DbConnection::getInstance()->Execute(
				'SELECT P.id, P.code, P.description, P.keywords, P.content, P.jsScript, 
						L.id, L.content, P.securePage 
				FROM sys_page P 
				INNER JOIN sys_layout L on L.id = P.layout_id 
				where P.code = <s:code/> and P.site_id = <n:siteId/>', 
						array( 's:code' => $this->_codePage, 'n:siteId' => $this->_siteId ));
		} else {
			DbConnection::getInstance()->Execute(
				'SELECT P.id, P.code, P.description, P.keywords, P.content, P.jsScript,
						L.id, L.content, P.securePage 
				FROM sys_page P 
				INNER JOIN sys_layout L on L.id = P.layout_id 
				INNER JOIN sys_enum E on P.behavior = E.id
				WHERE E.code = \'HOME\' and E.type = \'PAGE_BEHAVIOR\' and P.site_id = <n:siteId/>',
				array( 'n:siteId' => $this->_siteId ));
		}
		
		
		if ( $row = DbConnection::getInstance()->nextRow()){
			$i = 0;
			$this->_idPage = $row[$i++];
			$this->_codePage = $row[$i++];
			$this->_descPage = $row[$i++];
			$this->_keywordsPage = $row[$i++];
			$this->_htmlContent = $row[$i++];
			$this->_jsScript = $row[$i++];
			$this->_idLayout = $row[$i++];
			$this->_htmlLayout = $row[$i++];
			$this->_isSecurePage = $row[$i++];
		} else {
			header('HTTP/1.0 404 Not Found');
	  		exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found for this site (id=$this->_siteId.)");		
		}

	}

	public function validateAuthorization( ) {
		if (!$this->_isSecurePage)
			return true;
	/*
		
		if (isset($_POST['login']))		
		{			
			if (isset($_POST['pwd']))
			{
			echo '<HR/>recup param</HR>';
				if ($this->_userMembership->Authentify($_POST['login'], $_POST['pwd']))
				{
					$url = 'Location: ' . $this->_siteUrl;
					if (isset($_GET['back']))
						$url .= '?p=' . $_GET['back'];

					header($url);
					exit();					
				}
			}
		}		
		
		return $this->validateAuthentication();*/
		
		return true;
	}


	/**
	* Retourne vrai si l'utilisateur a le droit d'accéder à 
	* cette page ou si la page est en accès libre.
	* 
	*/
	public function validateAuthentication ( ) {
		//use $this->_userMembership->getPermission();
		return $this->_userMembership->isAuthenticated();
	}
	
	/**
	* @todo titre et description de la page
	* 
	*/
	public function writeHtmlHeader() {
		echo '<HEAD>';
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
		echo '<meta http-equiv="X-UA-Compatible" content="IE=9">';
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
		echo '<meta name="description" content="'; echo htmlentities($this->_descPage); echo '">';
		echo '<meta name="keywords" content="'; echo htmlentities($this->_keywordsPage); echo '">';

		echo '<title>' . AppConfig::getInstance()->SITE_TITLE . '</title>';
		
		$this->addJsLink('http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
		$this->addJsLink('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js');
		$this->addJsLink('alias.php/scripts/alias.js');
		if(AppConfig::getInstance()->isDebug())
		{
			$this->addJsLink('alias.php/scripts/actionsMenu.js');			
		}

		DbConnection::getInstance()->Execute(
			'SELECT R.fileName, R.version FROM sys_resource R 
			 inner join sys_enum T on R.enum_idTypeResource = T.id 
			 inner join sys_page_has_resources TL on R.id = TL.resource_id 
			 where T.code = \'JS\' and TL.page_id = <n:idPage/> 
			 UNION 
			 SELECT R.fileName, R.version FROM sys_resource R 
			 inner join sys_enum T on R.enum_idTypeResource = T.id 
			 inner join sys_layout_has_resources TL on R.id = TL.resource_id 
			 where T.code = \'JS\' and TL.layout_id = <n:idLayout/> ', 
						array( 
							'n:idPage' => $this->_idPage, 
							'n:idLayout' => $this->_idLayout));

		while ( $row = DbConnection::getInstance()->nextRow()){
			$this->addJsLink($row[0], $row[1]);
		}

		$this->addCssLink('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css');
		$this->addCssLink('http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/smoothness/jquery-ui.min.css');
		

		DbConnection::getInstance()->Execute(
			'SELECT R.fileName, R.version FROM sys_resource R 
			 inner join sys_enum T on R.enum_idTypeResource = T.id 
			 inner join sys_page_has_resources TL on R.id = TL.resource_id 
			 where T.code = \'CSS\' and TL.page_id = <n:idPage/> 
			 UNION 
			 SELECT R.fileName, R.version FROM sys_resource R 
			 inner join sys_enum T on R.enum_idTypeResource = T.id 
			 inner join sys_layout_has_resources TL on R.id = TL.resource_id 
			 where T.code = \'CSS\' and TL.layout_id = <n:idLayout/> ', 
						array( 
							'n:idPage' => $this->_idPage, 
							'n:idLayout' => $this->_idLayout));

		while ( $row = DbConnection::getInstance()->nextRow()){
			$this->addCssLink($row[0], $row[1]);
		}
		
		if  (isset($this->_jsScript) && $this->_jsScript != '') {
			echo '<script type="text/javascript">';
			$bits=explode("--}",$this->_jsScript); 
			foreach($bits as $bit) { 
				$parts=explode("{--",$bit); 
				echo $parts[0]; 
				if(isset($parts[1])) 
					$this->renderTemplateVariable($parts[1]);
			} 
			echo '</script>';			
		}
		
		echo '</HEAD>';		
	}

	private function addJsLink($fileUrl, $version = '')
	{
		echo '<script type="text/javascript" src="';
		if (substr($fileUrl, 0, 7) != 'http://')
			echo $this->_siteUrl;
		echo $fileUrl;
		if ($version != '')
			echo '?v='.$version;
		echo '"></script>';
	}


	private function addCssLink($fileUrl, $version = '')
	{
		echo '<link rel="stylesheet" type="text/css" href="';
		if (substr($fileUrl, 0, 7) != 'http://')
			echo $this->_siteUrl;
		echo $fileUrl;
		if ($version != '')
			echo '?v='.$version;
		echo '">';
	}

	public function writeHtmlLayout(){
		$bits=explode("--}",$this->_htmlLayout); 
		foreach($bits as $bit) { 
			$parts=explode("{--",$bit); 
			echo $parts[0]; 
			if(isset($parts[1])) 
				$this->renderTemplateVariable($parts[1]);
		} 
	}

	public function writeHtmlContent(){
		echo '<div id=content_data>';
		echo $this->_htmlContent;
		echo '</div>'; 
		
		echo '<ul id="menu" class=".ui-menu">	<li action="createPage"><a href="#">Créer une page</a></li>	<li action="editPage"><a href="#">Modifier cette page</a></li>	<li  class="ui-state-disabled"><a href="#">propriété de cette page</a></li>	<li class="ui-state-disabled"><a href="#">Parametres</a></li> 	</ul>';
		

	}

	public function end ( ) {
		ob_end_flush();
	}	
	
	
	/**
	* récupere la page d'authentification de la base de données 
	* et renvoie vers celle-ci
	* 
	*/
	public function disconnect ( ) {
		session_destroy();
		header('Location: ' . $this->_siteUrl);
  		exit();
	}
	
	public function logon ( ) {
		DbConnection::getInstance()->Execute(
					'SELECT P.code FROM sys_page P inner join sys_enum E on P.behavior = E.id where E.code = \'LOGIN\' and E.type = \'PAGE_BEHAVIOR\' ');
		
		if ( $row = DbConnection::getInstance()->nextRow()){
			header('Location: ' . $this->_siteUrl . '?p='.$row[0].'&back='.$this->_codePage);
  			exit();
		} else {
			header('HTTP/1.0 404 Not Found');
			// la page de login n'est pas (ou mal) paramétrée
	  		exit("<h1>404 Not Found</h1>\nThe login page could not be found.");		
		}

	}

	
	private function renderTemplateVariable($varName) {
		$parts=explode("::",$varName); 
		
		if(!isset($parts[1])) {
			echo 'Variable [['.$varaName.']] mal formée';
			return;
		}
		
		$functionName = "get".$parts[1];
		
		switch (strtolower($parts[0])) {
			case 'membership':
				echo $this->_userMembership->$functionName();
				break;
			default:
				echo 'Variable [['.$varaName.']] inconnue';
			return;
		}
		
	}
	
	private function buildUrl($relativeUrl) {
	    $s = &$_SERVER;
	    $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
	    $sp = strtolower($s['SERVER_PROTOCOL']);
	    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
	    $port = $s['SERVER_PORT'];
	    $port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
	    $host = isset($s['HTTP_X_FORWARDED_HOST']) ? $s['HTTP_X_FORWARDED_HOST'] : isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];
	    return $protocol . '://' . $host . $port . $relativeUrl;
	}
	
} // END class